# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 聚合管道操作之merge用法.py
# @Author: dongguangwen
# @Date  : 2025-06-15 17:59
from datetime import datetime
from pymongo import MongoClient


# 连接 MongoDB
client = MongoClient("mongodb://root:root123@192.168.1.119:27017/")
db = client["learning_mongodb"]
collection = db["users"]


# 插入测试数据（如果你没有数据）
test_users = [
    {"name": "Alice", "address": {"city": "Shanghai2"}, "is_active": True, "age": 28},
    {"name": "Bob", "address": {"city": "Beijing2"}, "is_active": True, "age": 32},
    {"name": "Charlie", "address": {"city": "Shanghai2"}, "is_active": False, "age": 25},
    {"name": "David", "address": {"city": "Guangzhou2"}, "is_active": True, "age": 40},
    {"name": "Eve", "address": {"city": "Beijing2"}, "is_active": True, "age": 22},
]
collection.insert_many(test_users)
print("已插入测试数据")

# 首次运行创建 user_stats 集合并插入初始数据
user_stats = db["user_stats"]
# user_stats.insert_one({"_id": "Shanghai", "user_count": 1, "last_updated": datetime.utcnow()})

# 定义聚合管道（带 $merge）
pipeline = [
    {"$match": {"is_active": True}},
    {
        "$group": {
            "_id": "$address.city",
            "user_count": {"$sum": 1}
        }
    },
    {
        "$merge": {
            "into": "user_stats",  # 合并到的目标集合
            "on": "_id",           # 按 _id 字段进行匹配
            "whenMatched": "merge",  # 匹配时更新
            "whenNotMatched": "insert"  # 不匹配时插入新文档
        }
    }
]

# 执行聚合
result = list(collection.aggregate(pipeline))
print(result)

# 输出合并后的结果
print("\n写入结果（使用 $merge）：")
for doc in user_stats.find():
    print(doc)

"""
已插入测试数据
[]

写入结果（使用 $merge）：
{'_id': 'Shanghai', 'user_count': 1, 'last_updated': datetime.datetime(2025, 6, 15, 10, 1, 52, 434000)}
{'_id': 'Shanghai2', 'user_count': 1}
{'_id': 'Beijing2', 'user_count': 2}
{'_id': 'Guangzhou2', 'user_count': 1}
"""